<script lang="ts" setup>
import type { BaseinfoDemandApi } from '#/api/csyt/baseinfodemand';
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { message, Tabs } from 'ant-design-vue';
import { useVbenForm } from '#/adapter/form';
import {createBaseinfoDemand, getBaseinfoDemand, updateBaseinfoDemand,} from '#/api/csyt/baseinfodemand';
import { $t } from '#/locales';
import {useFormQuery, useFormSchema} from '../data';
import BaseinfoIndicatorForm from './baseinfo-indicator-form.vue';
import type { VxeGridProps } from '#/adapter/vxe-table';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { Button } from 'ant-design-vue';
import {getBaseinfoChatInfo, deleteBaseinfoChatDelete, createBaseinfoChat, createBaseinfoChatadds,getBaseinfoChatLable} from '#/api/csyt/baseinfochat';
import type { BaseinfoChatApi } from '#/api/csyt/baseinfochat';
import {  confirm } from '@vben/common-ui';
const emit = defineEmits(['success']);

const formData = ref({});


/** 子表的表单 */
const subTabsName = ref('baseinfoIndicator');
const baseinfoIndicatorFormRef =
  ref<InstanceType<typeof BaseinfoIndicatorForm>>();

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    // 一列配置
    // formItemClass: 'col-span-2',
    // labelWidth: 80,
  },
  // 一共2列
  wrapperClass: 'grid-cols-4',
  layout: 'horizontal',
  schema: useFormQuery(),
  showDefaultActions: false,
});
const productList=ref([]);
const lableinfoList =ref([]);
const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    // 校验子表单
    modalApi.lock();
    // 提交表单
    const data =
      (await formApi.getValues()) as BaseinfoDemandApi.BaseinfoDemand;
    // 拼接子表的数据
    data.baseinfoIndicators = baseinfoIndicatorFormRef.value?.getData();
    try {
      await (formData.value?.id
        ? updateBaseinfoDemand(data)
        : createBaseinfoDemand(data));
      // 关闭并提示
      await modalApi.close();
      emit('success');
      message.success($t('ui.actionMessage.operationSuccess'));
    } finally {
      modalApi.unlock();
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      formData.value = {};
      return;
    }
    // 加载数据
    let data = modalApi.getData();
    // console.log(data)
    if (!data) {
      return;
    }
    if (data.chatNo) {
      modalApi.lock();
      try {
        data = await getBaseinfoChatInfo({chatNo:data.chatNo});
      } finally {
        modalApi.unlock();
      }
    }
    console.log(data)
    // 设置到 values
    formData.value = data;

    productList.value=formData.value.productInfo.lableinfoList;
    lableinfoList.value=formData.value.demandInfo.indicatorList;
    await formApi.setValues(formData.value);
    gridApi.query();
    gridApiNew.query();
    onResh();
  },
});


const gridOptions: VxeGridProps<RowType> = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
  },
  columns: [
    { field: 'targetName', title: '指标名称' },
    { field: 'targetNo', title: '指标编号' },
    { field: 'targetDescription', title: '指标描述' },
    { field: 'ruleName', title: '规则名称' },
    { field: 'ruleDescription', title: '规则表述' },
  ],
  exportConfig: {},
  // height: 'auto', // 如果设置为 auto，则必须确保存在父节点且不允许存在相邻元素，否则会出现高度闪动问题
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        return lableinfoList.value
      },
    },
  },
  pagerConfig: {
    enabled: false,
  },
  sortConfig: {
    multiple: true,
  },
  toolbarConfig: {
    custom: false,
    export: false,
    refresh: false,
    zoom: false,
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions,
});
const dataValue=ref([])
//产品列表
const [GridNew, gridApiNew] = useVbenVxeGrid({
  gridOptions:{
    checkboxConfig: {
      highlight: true,
      labelField: 'name',
    },
    columns: [
      { field: 'lableName', title: '标签名称' },
      { field: 'lableNo', title: '标签编号' },
      { field: 'lableType', title: '标签类型' },
      { field: 'lableDescription', title: '标签描述' },
      { field: 'lableTemp', title: '标签示例' },
    ],
    exportConfig: {},
    // height: 'auto', // 如果设置为 auto，则必须确保存在父节点且不允许存在相邻元素，否则会出现高度闪动问题
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }) => {
          return productList.value
          // return await getExampleTableApi({
          //   page: page.currentPage,
          //   pageSize: page.pageSize,
          // });
        },
      },
    },
    pagerConfig: {
      enabled: false,
    },
    sortConfig: {
      multiple: true,
    },
    toolbarConfig: {
      custom: false,
      export: false,
      refresh: false,
      zoom: false,
    },
  },


});
// 编辑列表
const [GridEdit, gridApiEdit] = useVbenVxeGrid({
  gridOptions:{
    height: "200px",
    checkboxConfig: {
      highlight: true,
      labelField: 'name',
    },
    columns: [
      { align: 'left', title: '', type: 'checkbox', width: 100 },
      { title: '匹配id',  field: 'id',},
      {  field: 'demandNo', title: '需求指标' , slots: { default: 'demandIndicator' },},
      { field: 'targetNo', title: '产品标签', slots: { default: 'productLableinfo' } },
    ],
    exportConfig: {},
    // height: 'auto', // 如果设置为 auto，则必须确保存在父节点且不允许存在相邻元素，否则会出现高度闪动问题
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }) => {
          console.log(formData.value)

          return dataValue.value

        },
      },
    },
    pagerConfig: {
      enabled: false,
    },
    sortConfig: {
      multiple: true,
    },
    toolbarConfig: {
      custom: false,
      export: false,
      refresh: false,
      zoom: false,
    },

  },
  gridEvents: {
    checkboxAll: handleRowCheckboxChange,
    checkboxChange: handleRowCheckboxChange,
  },

});
async function onResh(){
  const result = await getBaseinfoChatLable({chatNo:formData.value.chatNo})
  result.list.map((item,index)=>{
    item.orderNo=index+1
    item.chatNo=formData.value.chatNo

  })
  dataValue.value=result.list;
  gridApiEdit.query();
}

const checkedIds = ref<number[]>([]);
const currentRow=ref({})
// 选择框

function handleRowCheckboxChange({records}: { records: BaseinfoChatApi.BaseinfoChatData[];}){
  checkedIds.value = records.map((item) => item.id?item.id:item.orderNo);
  currentRow.value=records[0]
}

// 添加
function addData(){
  dataValue.value.push( {
    orderNo:dataValue.value.length+1,
    chatNo:formData.value.chatNo,
    demandNo:undefined, //需求
    targetNo:undefined, //指标编号
  })
  gridApiEdit.query();
}
// 单个删除
async function oneDelete(){
  if(currentRow.value.id){
    await deleteBaseinfoChatDelete(checkedIds.value);
    dataValue.value=dataValue.value.filter(item=>{
      return item.id!=checkedIds.value[0]
    });
  }else{
    dataValue.value=dataValue.value.filter(item=>{
      return item.orderNo!=checkedIds.value[0]
    });
  }

  gridApiEdit.query();

}
function returnClick(){
   modalApi.close();
}
// 批量删除
async function deleteClick(){
  await confirm('是否确认删除所有二级匹配？')
  let a=dataValue.value.map((item) => item.id);
  await deleteBaseinfoChatDelete(a);
  message.success( $t('ui.actionMessage.operationSuccess') );
  onResh()
}

// 确认所有匹配
async function addDataALL(){
  await confirm('是否确认所有匹配？')
  let form={
    indicatorLableinfoList:dataValue.value,
    chatNo:formData.value.chatNo
  }
  let result = await createBaseinfoChatadds(form)
  message.success( $t('ui.actionMessage.operationSuccess') );
  onResh()

}
</script>

<template>
  <Modal title="" class="w-1/3">
    <Form class="mx-4" />
    <a-divider style="margin:0 !important;">需求规则信息</a-divider>
    <Grid :key="1" style="height:200px !important;"></Grid>
    <a-divider style="margin:0 !important;">产品指标信息</a-divider>
    <GridNew :key="3" style="height:200px !important;"></GridNew>
    <div>
      <Button class="mr-2" type="primary" @click="addData">添 加</Button>
      <Button  class="mr-2"  type="primary" :disabled="checkedIds.value&&checkedIds.value.length!=1" danger @click="oneDelete">删 除</Button>
    </div>
    <GridEdit style="height:200px !important;">
      <template #demandIndicator="{ row }">
        <a-select style="width:100%" ref="select" v-model:value="row.demandNo">
          <a-select-option v-for="(item,index) in lableinfoList" :value="Number(item.targetNo)" :key="index">{{item.targetName}}</a-select-option>

        </a-select>
      </template>
      <template #productLableinfo="{ row }">
        <a-select ref="select" style="width:100%" v-model:value="row.targetNo">
          <a-select-option v-for="(item,index) in productList" :value="Number(item.lableNo)" :key="index">{{item.lableName}}</a-select-option>
        </a-select>
      </template>

    </GridEdit>
    <div style="margin-top:15px;text-align: center;">
      <Button class="mr-2" type="primary" @click="addDataALL">确认匹配</Button>
      <Button class="mr-2"  type="primary" danger @click="deleteClick">删除所有匹配</Button>
      <Button class="mr-2"    @click="returnClick">返 回</Button>
    </div>
  </Modal>
</template>
